package com.tensquare.article.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.tensquare.article.dao.ArticleDao;
import com.tensquare.article.pojo.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import util.IdWorker;

import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class ArticleService {
    @Autowired
    private ArticleDao articleDao;

    @Autowired
    private IdWorker idWorker;





    public List<Article> finfAll() {
        return articleDao.selectList(null);
    }

    public Article findById(String articleId) {
        return articleDao.selectById(articleId);
    }

    public void save(Article article) {
        //使用ID生成器生产ID
        String id = idWorker.nextId() + "";
        article.setId(id);

        //初始化数据 默认初始浏览量 点赞数 评论数为0
        article.setVisits(0);
        article.setThumbup(0);
        article.setComment(0);

        articleDao.insert(article);
    }

    public void updateById(Article article){
        articleDao.updateById(article);
    }

    public void deleteById(String articleId) {
        articleDao.deleteById(articleId);
    }

    public Page<Article> findByPage(Integer page, Integer size, Map<String, Object> map) {
        //设置条件
        EntityWrapper<Article> wrapper=new EntityWrapper<>();
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            if(map.get(key)!=null){
                wrapper.eq(key,map.get(key));
            }
        }
        //设置分页参数
        Page<Article>pageData=new Page<>(page,size);

        //分页查询
        List<Article> articleList = articleDao.selectPage(pageData, wrapper);

        pageData.setRecords(articleList);

        return pageData;
    }
}
